import React, { useState, useEffect, useRef } from 'react';
import { Table, Button, Input, Modal, Form, InputNumber, Radio, Space, Tag, Spin, message, Popconfirm } from "antd";
import axios from 'axios';
import type { ColumnsType } from 'antd/es/table';

// 定义API基础URL，方便统一管理
const API_BASE_URL = 'http://localhost:5017/api/Box';

// 自定义样式
const styles = {
  requiredLabel: {
    '&::before': {
      content: '"*"',
      color: '#ff4d4f',
      marginRight: 4,
    }
  }
};

interface BoxData {
  id: string;
  boxName: string;
  length: string | number;
  width: string | number;
  height: string | number;
  remark: string;
  state: number;
}

const Box = () => {
  // 定义状态变量
  const [data, setData] = useState<BoxData[]>([]); // 箱子列表数据
  const [pageIndex, setPageIndex] = useState(1); // 当前页码
  const [pageSize, setPageSize] = useState(10); // 每页显示条数
  const [totalCount, setTotalCount] = useState(0); // 总条数
  const [showModal, setShowModal] = useState(false); // 是否显示弹框
  const [form, setForm] = useState<BoxData>({ id: '', boxName: '', length: '', width: '', height: '', remark: '', state: 0 }); // 表单数据
  const [isEdit, setIsEdit] = useState(false); // 是否为编辑状态
  const [loading, setLoading] = useState(false); // 是否加载中
  const [searchBoxName, setSearchBoxName] = useState('');
  const [formRef] = Form.useForm();
  const [submitting, setSubmitting] = useState(false); // 添加提交状态
  const submitBtnRef = useRef<boolean>(false); // 防止重复提交

  // 查询箱子列表
  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await axios.get(`${API_BASE_URL}/BoxQuery`, {
        params: { PageIndex: pageIndex, PageSize: pageSize, boxName: searchBoxName }
      });
      console.log('获取数据响应:', res);
      setData(res.data.items || []);
      setTotalCount(res.data.totalCount || 0);
    } catch (err: any) {
      console.error('获取数据失败:', err);
      message.error('获取数据失败: ' + (err.response?.data?.message || err.message));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [pageIndex, pageSize]);

  // 表单输入处理
  const handleInput = (name: string, value: any) => {
    setForm(prev => ({ ...prev, [name]: value }));
  };

  // 打开新增弹框
  const openAdd = () => {
    setForm({ id: '', boxName: '', length: '', width: '', height: '', remark: '', state: 0 });
    setIsEdit(false);
    setShowModal(true);
    formRef.resetFields();
  };

  // 打开编辑弹框
  const openEdit = (row: BoxData) => {
    setForm({ ...row });
    setIsEdit(true);
    setShowModal(true);
    formRef.setFieldsValue(row);
  };

  // 新增或编辑提交
  const handleSubmit = async () => {
    // 防止重复提交
    if (submitBtnRef.current) {
      return;
    }
    
    submitBtnRef.current = true;
    setSubmitting(true);
    
    try {
      // 表单验证
      const values = await formRef.validateFields();
      
      // 构建提交数据
      const payload = {
        boxName: values.boxName,
        length: Number(values.length),
        width: Number(values.width),
        height: Number(values.height),
        remark: values.remark || '',
        state: Number(values.state)
      };
      
      console.log('提交数据:', payload);
      
      if (isEdit) {
        try {
          const response = await axios.put(`${API_BASE_URL}/UpdeteBox`, { ...payload, id: form.id });
          console.log('编辑响应:', response);
          if (response.status === 200) {
            message.success('修改成功');
            setShowModal(false);
            formRef.resetFields();
            setForm({ id: '', boxName: '', length: '', width: '', height: '', remark: '', state: 0 });
            fetchData();
          } else {
            message.error('修改失败');
          }
        } catch (err: any) {
          console.error('编辑失败:', err);
          message.error('修改失败: ' + (err.response?.data?.message || err.message));
        }
      } else {
        try {
          const response = await axios.post(`${API_BASE_URL}/CreateBox`, payload);
          console.log('添加响应:', response);
          if (response.status === 200 || response.status === 201) {
            message.success('添加成功');
            setShowModal(false);
            formRef.resetFields();
            setForm({ id: '', boxName: '', length: '', width: '', height: '', remark: '', state: 0 });
            fetchData();
          } else {
            message.error('添加失败');
          }
        } catch (err: any) {
          console.error('添加失败:', err);
          message.error('添加失败: ' + (err.response?.data?.message || err.message));
        }
      }
    } catch (err: any) {
      console.error('表单验证失败:', err);
      message.error('提交失败，请检查表单');
    } finally {
      setSubmitting(false);
      // 延迟重置防抖标志
      setTimeout(() => {
        submitBtnRef.current = false;
      }, 300);
    }
  };

  // 取消操作时重置表单
  const handleCancel = () => {
    setShowModal(false);
    formRef.resetFields();
    setForm({ id: '', boxName: '', length: '', width: '', height: '', remark: '', state: 0 });
  };

  // 删除
  const handleDelete = async (id: string) => {
    try {
      const response = await axios.delete(`${API_BASE_URL}/DelBox`, { data: { id } });
      console.log('删除响应:', response);
      if (response.status === 200) {
        message.success('删除成功');
        fetchData();
      } else {
        message.error('删除失败');
      }
    } catch (err: any) {
      console.error('删除失败:', err);
      message.error('删除失败: ' + (err.response?.data?.message || err.message));
    }
  };

  const columns: ColumnsType<BoxData> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '名称',
      dataIndex: 'boxName',
      key: 'boxName',
    },
    {
      title: '长(CM)',
      dataIndex: 'length',
      key: 'length',
      render: (text) => Number(text).toFixed(2),
    },
    {
      title: '宽(CM)',
      dataIndex: 'width',
      key: 'width',
      render: (text) => Number(text).toFixed(2),
    },
    {
      title: '高(CM)',
      dataIndex: 'height',
      key: 'height',
      render: (text) => Number(text).toFixed(2),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (state) => (
        <Tag color={state === 0 ? 'success' : 'error'}>
          {state === 0 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="primary" size="small" onClick={() => openEdit(record)}>
            修改
          </Button>
          <Popconfirm
            title="确定要删除吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button danger size="small">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 20, background: '#f5f7fa', minHeight: '100vh' }}>
      {/* 查询条件 */}
      <Space style={{ marginBottom: 16 }}>
        <Input
          placeholder="箱子型号名称"
          value={searchBoxName}
          onChange={e => setSearchBoxName(e.target.value)}
          onPressEnter={fetchData}
          style={{ width: 200 }}
        />
        <Button type="primary" onClick={() => { setPageIndex(1); fetchData(); }}>
          查询
        </Button>
        <Button onClick={() => { setSearchBoxName(''); setPageIndex(1); fetchData(); }}>
          重置
        </Button>
      </Space>
      
      {/* 顶部按钮 */}
      <div style={{ marginBottom: 16 }}>
        <Button type="dashed" onClick={openAdd}>
          + 箱子型号添加
        </Button>
      </div>
      
      {/* 表格 */}
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{
          current: pageIndex,
          pageSize: pageSize,
          total: totalCount,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, pageSize) => {
            setPageIndex(page);
            setPageSize(pageSize);
          },
          pageSizeOptions: ['3', '5', '8', '10', '20', '50'],
        }}
      />
      
      {/* 弹框 */}
      <Modal
        title={isEdit ? '编辑箱子型号' : '新增箱子型号'}
        open={showModal}
        onOk={handleSubmit}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        destroyOnHidden={true}
        confirmLoading={submitting}
        maskClosable={false}
      >
        <Form 
          form={formRef} 
          layout="vertical" 
          preserve={false}
        >
          <Form.Item
            name="boxName"
            label="名称"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input placeholder="请输入名称" maxLength={50} />
          </Form.Item>
          
          <Form.Item
            name="length"
            label="长(CM)"
            rules={[{ required: true, message: '请输入长度' }]}
          >
            <InputNumber style={{ width: '100%' }} placeholder="请输入长度" min={0} precision={2} />
          </Form.Item>
          
          <Form.Item
            name="width"
            label="宽(CM)"
            rules={[{ required: true, message: '请输入宽度' }]}
          >
            <InputNumber style={{ width: '100%' }} placeholder="请输入宽度" min={0} precision={2} />
          </Form.Item>
          
          <Form.Item
            name="height"
            label="高(CM)"
            rules={[{ required: true, message: '请输入高度' }]}
          >
            <InputNumber style={{ width: '100%' }} placeholder="请输入高度" min={0} precision={2} />
          </Form.Item>
          
          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea 
              placeholder="请输入备注（最多200字）" 
              rows={4} 
              maxLength={200} 
              showCount
            />
          </Form.Item>
          
          <Form.Item
            name="state"
            label="状态"
            initialValue={0}
          >
            <Radio.Group>
              <Radio value={0}>启用</Radio>
              <Radio value={1}>禁用</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Box;
